Skip to main content

Python Dictionaries

Dictionaries in Python are mutable, unordered collections that store key-value pairs. Each key in a dictionary must be unique, and the keys are used to access the associated values. Here’s a comprehensive guide to working with dictionaries in Python:

Creating Dictionaries

You can create dictionaries using curly braces {} with key-value pairs separated by colons.

# Creating an empty dictionary

empty_dict = {}

# Creating a dictionary with some key-value pairs

student = {

    "name": "John Doe",

    "age": 20,

    "courses": ["Math", "Computer Science"]

}



Accessing Values

You can access values in a dictionary by using their keys.

# Accessing values by key

print(student["name"])  # Output: John Doe

print(student["age"])   # Output: 20

print(student["courses"])  # Output: ['Math', 'Computer Science']



Modifying Dictionaries

You can modify the values associated with a specific key, add new key-value pairs, and delete existing ones.

Changing Values

# Changing the value associated with a key

 student["age"] = 21

 print(student["age"])  # Output: 21

 



Adding Key-Value Pairs

# Adding a new key-value pair

student["grade"] = "A"

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science'], 'grade': 'A'}


Removing Key-Value Pairs

# Removing a key-value pair using del

del student["grade"]

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science']}

# Removing a key-value pair using pop()

age = student.pop("age")

print(age)      # Output: 21

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science']}



Dictionary Methods

Dictionaries come with several built-in methods.

keys(), values(), and items()

These methods are used to access the keys, values, and key-value pairs in the dictionary.

print(student.keys())   # Output: dict_keys(['name', 'courses'])

print(student.values()) # Output: dict_values(['John Doe', ['Math', 'Computer Science']])

print(student.items())  # Output: dict_items([('name', 'John Doe'), ('courses', ['Math', 'Computer Science'])])



update()

This method updates the dictionary with key-value pairs from another dictionary or from an iterable of key-value pairs.

# Updating a dictionary with another dictionary

student.update({"age": 21, "grade": "A"})

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 21, 'grade': 'A'}

# Updating a dictionary with an iterable of key-value pairs

student.update([("age", 22), ("grade", "B")])

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22, 'grade': 'B'}



get()

This method returns the value for a specified key if the key is in the dictionary, otherwise it returns a default value.

print(student.get("name"))       # Output: John Doe

print(student.get("grade"))      # Output: B

print(student.get("address", "Not Available"))  # Output: Not Available



popitem()

This method removes and returns the last inserted key-value pair as a tuple.

last_item = student.popitem()

print(last_item)  # Output: ('grade', 'B')

print(student)    # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22}



clear()

This method removes all items from the dictionary.

student.clear()

print(student)  # Output: {}

 

Summary

  • Creating Dictionaries: Use curly braces {} with key-value pairs separated by colons.
  • Accessing Values: Use keys to access values.
  • Modifying Dictionaries: Add, change, and remove key-value pairs.
  • Dictionary Methods: Use methods like keys(), values(), items(), update(), get(), popitem(), and clear().
  • Iterating Over Dictionaries: Iterate over keys, values, and key-value pairs.

Dictionaries are highly versatile and useful for various applications, including data representation, counting, and simple databases. Mastering dictionaries will greatly enhance your ability to work with structured data in Python.

 

 

Comments

Popular posts from this blog

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.